import hashlib
import leancloud
import sys
sys.path.append("..")
import Cust.leancloudapi
GetApi = Cust.leancloudapi.GetApi()
Admin = GetApi.getAdmin()
class User:
    def  md5(self,password):
        m = hashlib.md5()
        m.update(password)
        return m.hexdigest()
    def  queryUser(self,name,password):
        query1 = Admin.query
        password1 = self.md5(password)
        res =  query1.equal_to('AdminName',name).find()
        for item in res:
            pastr = item.get('Password')
            role = item.get('RoleType')
            if(pastr==password1):
                return role
            else:
                return 2
    def  insertAdmin(self,name):
        adduser = Admin()
        pstr = self.md5('0123456')
        adduser.set('AdminName',name)
        adduser.set('Password',pstr)
        try:
            adduser.save()
            return 810
        except Exception as e:
            print e.message
            return 811
    def  moifyName(self,id,name):
        updateadmin  = Admin.create_without_data(id)
        updateadmin.set('AdminName',name)
        try:
            updateadmin.save()
            return 830
        except Exception as e:
            return 831
    def  resetPassword(self,id):
        updateadmin  = Admin.create_without_data(id)
        pstr = self.md5('0123456')
        updateadmin.set('Password',pstr)
        try:
            updateadmin.save()
            return 840
        except Exception as e:
            print e.message
            return 841
    def  getUser(self,id):
        queryuser = Admin.create_without_data(id)
        queryuser.fetch()
        username = queryuser.get('AdminName')
        user = {'id':id,'name':username}
        return user
    def  getAllUser(self):
        query= Admin.query
       
        res =  query.equal_to('RoleType',0).find()
        user_list = []
        for item in res:
            username = item.get('AdminName') 
            user = {'id':item.id,'name':username}    
            user_list.append(user)
        return user_list   

    def  delAdmin(self,id):
        delAdmin = Admin.create_without_data(id)
        try:
            delAdmin.destroy()
            return 820
        except Exception as e:
            print e.message
            return 821
   
    def   modifyPassword(self,id,password):
        modifyPass = Admin.create_without_data(id)
        passwordstr = self.md5(password) 
        modifyPass.set('Password',passwordstr)
        try:
            modifyPass.save()
            return 850
        except Exception as e:
            print e.message
            return 851
    def    getUserByname(self,name):
        query1 = Admin.query
        res =  query1.equal_to('AdminName',name).find()
        for item in res:
            pastr = item.get('Password')
            user = {'id':item.id,'name':name,'password':pastr}
            return user
